<template>
  <div class="map-container">
    <div class="map" :id="mapId"></div>
  </div>
</template>

<script>
import MapClass from "@/utils/mapClass";



export default {
  name: "Map",
  data() {
    return {
      mapId: "map" + new Date().getTime() + parseInt(Math.random() * 1000),
      mapClass: null,
    };
  },

  mounted() {
    if (window.AMap) {
      this.initMap();
    } else {
      window.addEventListener("mapReady", this.initMap);
    }
  },
  beforeDestroy() {
    this.map && this.map.destroy();
    window.removeEventListener("mapReady", this.initMap);
  },
  methods: {
    initMap() {
      if (this.map) return;
      const locationCenter = this.$store.state.locationCenter;
      this.map = new AMap.Map(this.mapId, {
        mapStyle: "amap://styles/normal",
        viewMode: "2D", //是否为3D地图模式
        zoom: 12, //初始化地图级别
        center: locationCenter
      });
      // 卫星地图切换
      this.map.addControl(new AMap.MapType());
      this.$emit("mapLoaded");
    },
    addMarkers(data) {
      if (data && data.length) {
        const list = [];
        data.forEach((item) => {
          if (item.location) {
            item.point = JSON.parse(item.location);
            item.name = item.deviceName || item.name;
            list.push(item);
          }
        });
        if (!this.mapClass) this.mapClass = new MapClass(this.map);
        const iconMarker = {
          icon: new AMap.Icon({
            image:"https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: [28, 36],
            imageSize: [28, 36],
          }),
        };

        const selIconMarker = {
          icon: new AMap.Icon({
            image: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
            size: [28, 36],
            imageSize: [28, 36],
          }),
        };
        this.mapClass.addMarkers("monitor",list,this.onClickLayer,iconMarker,selIconMarker);
      }
    },
    removeMarkers() {
      if(this.mapClass) {
        this.mapClass.removeLayer('monitor')
      }
    },
    // 点击了大头针
    onClickLayer(item) {
      console.log("点击了覆盖物：", item);
      this.$emit("handleClickMarker", item)
    },
    selMarker(item) {
      if(this.mapClass) {
        this.mapClass.activeLayer(item.id,'monitor')
      }
    }
  },
};
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  .map {
    width: 100%;
    height: 100%;
    min-width: 20px;
    min-height: 20px;
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
}
</style>
